var tmplate={
				"deliverLocationOption":'<option value="@{locationValue}" ccy="@{ccyValue}">@{locationName}</option>'
			};


function deliver() {
	this.callSuper();
	this.configuration = {
		'i18n': 'nls/deliver',
		'apis': '../../config/apis/deliver'
	};
	this._viewIndex = 'deliverLoading';
	this.bossAccount = null;
	this.gameSetupObj = {
		isEnableBonus : null,
		location:null,
		greenAmount : "9999",
		bonusAmount : "5",
		currency : null,
		greenMoney : "20",
		bonusMoney : "50"
	};
	this.totalPrizeSent = null;
	this.prizeSummary = null;
	this.userInfo = {};
	this.deviceId = null;
	this.gameId = null;
	// Nick added to retrieve duration from server
	this.duration = null;
	this.countdownID = null;
	this._currentSlideIndex = 0;
	//Bill updated for getGameBudget [start]
	this._gameBudget = [];
	this._location = null;
	this._totalBudget = null;
	this._remainBudget = null;
	//Bill updated for getGameBudget [end]
	
	this.constants = {
		splitPercent	: "25%",
		settingName		: 'setting',
		resultDisplayDuration	: 3000, //unit is ms
		windowWidth		: 0,
		waitingDuration	: 10000 //unit is ms
	}
	
	// Nick added for goTo unlock list if sb. won bonus
	this.endGameBonusAmount = 0;
	// Nick added for goTo unlock list if sb. won bonus
	
	//this.locationArray = ['hk','cn'];
}

// ==============================================================
// page parsing section [start]
// ==============================================================
deliver.prototype.deliverLoadingHasParsed = function () {
	var self=this;
	//alert(window.innerHeight+', '+window.innerWidth);
	self.constants.windowWidth = window.innerWidth;
	if(self.configuration.settings.isBrowser){
		self.callback4GetUserInfo({"account":"43211234","fullName":"John Smith","secureToken":"123123123123123","sponsorCode":"ABC","location":"HTSA","company":"GLTc"});
	}else{
		self.getCustomerInfo(self.callback4GetUserInfo);
	}


    //dave
    $('#bossCodediv_id').text(self.userInfo[self.getCustomerInfoKeys().sponsorCode]);//self.getCustomerInfoKeys().sponsorCode
    self.surplusMoney=4;
    if(self.surplusMoney <= 0){
        $('#shakeMessageTxt_div').show();
    }else{
        $('#shakeMessageTxt_div').hide();
    }

}
//Dave
function getUrlValueByName(paramName){
    var paramValue="";
    var urlthis=location.href;
    urlthis=urlthis.substring(urlthis.indexOf('?')+1,urlthis.length);
    var arr=urlthis.split('&');
    if(arr!=null){
        for(var i=0;i<arr.length;i++){
            var parmNameValue=arr[i].split('=');
            if(parmNameValue!=null&&parmNameValue.length==2){
                if(parmNameValue[0]==paramName){
                    paramValue=parmNameValue[1];
                    break;
                }
            }
        }
    }
    return paramValue;
}
deliver.prototype.deliverNowHasParsed = function () {
	var self=this;
	//Bill updated for getGameBudget [start]
	self.getGameBudget();
	//Bill updated for getGameBudget [end]
	//Bill implement the changes for sponsor code [start]
	iData.get('deliverNow_btn_info').click(function(){
		iData.get('deliverNow_channelCode').text(self.splitChannelCode(self.userInfo.sponsorCode));
		self.cancelShaking(self.showChannelCodeInfo);
	});
	iData.get('deliverNow_channelCodeInfo_close').click(function(){
		self.prepareShaking(self.hideChannelCodeInfo);
	});
	//Bill implement the changes for sponsor code [end]
	iData.get('deliverNow_btn_menu').click(function(){
		var toPage = 'file:///web/postlogon/menu/menu.html?state='+getUrlValueByName('state');
		self.cancelShaking(self.goTo, [toPage, true]);
	});
	iData.get('deliverNow_btn_unlockBonus').click(function(){
		var toPage = 'file:///web/postlogon/unlock/unlock.html?state='+getUrlValueByName('state');
		self.cancelShaking(self.goTo, [toPage, true]);
	});
	iData.get('deliverNow_btn_dashboard').click(function(){
		var toPage = 'file:///web/postlogon/dashboard/dashboard.html';
		self.cancelShaking(self.goTo, [toPage, true]);
	});
	iData.get('deliverNow_btn_deliver').click(function(){
		return ;
	});
	
	iData.get('uniqCode').text(self.userInfo.sponsorCode);
	
	// change by daniel
	self.updateSettingLocation(self.configuration.settings.GreenPacketLocation);
	
	iData.get('deliverNow_input_warpper').on('input', 'input[type=tel]', function(){
		//console.log("change");
		self.updateSettingStatus();
	});
	
	iData.get('deliverLocation').val(self.gameSetupObj.location);
	
	iData.get('deliverLocation').on('change',function(){
		var ccy = $(this).find('option[value='+$(this).val()+']').attr('ccy');
		iData.get('deliverCurrencyList').each(function(i){
			$(this).html(ccy);	
		});
	});
	
	
	iData.get('deliverNow_btn_setting').click(function(){

		iData.get('deliverLocation').val(self.gameSetupObj.location);
		iData.get('deliverCurrencyList').each(function(i){
			$(this).html(self.gameSetupObj.currency);	
		});
		iData.get('deliverGreenMoney').val(self.gameSetupObj.greenMoney);
		iData.get('deliverBonusMoney').val(self.gameSetupObj.bonusMoney);
		iData.get('deliverBonusAmount').val(self.gameSetupObj.bonusAmount);
		iData.get('deliverGreenAmount').val(self.gameSetupObj.greenAmount);
		//Dave
        $('.ui-popup-item input').click(function(){
            var t=$(this).val();
            $(this).focus().val(t);
        });
        //Dave
		self.cancelShaking(self.showSetting);
	});
	// change by daniel end
	
	iData.get('deliverNow_setting_save').click(function(){
		if(!$(this).hasClass('disabled')){
			self.gameSetupObj.location = iData.get('deliverLocation').val();
			self.gameSetupObj.currency = iData.get('deliverLocation').find('option[value='+self.gameSetupObj.location+']').attr('ccy');
			self.gameSetupObj.greenMoney = iData.get('deliverGreenMoney').val();
			self.gameSetupObj.bonusMoney = iData.get('deliverBonusMoney').val();
			self.gameSetupObj.bonusAmount = iData.get('deliverBonusAmount').val();
			self.gameSetupObj.greenAmount = iData.get('deliverGreenAmount').val();
		
			self.setSetting();
		}
	});
	iData.get('deliverNow_setting_cancel').click(function(){
		
		iData.get('deliverLocation').each(function(i){
			if ($(this).val() === self.gameSetupObj.location) {
				$(this).attr('checked','checked');
			}else{
				$(this).removeAttr('checked');
			}
		});
		iData.get('deliverCurrencyList').each(function(i){
			$(this).html(self.gameSetupObj.currency);	
		});
		iData.get('deliverGreenMoney').val(self.gameSetupObj.greenMoney);
		iData.get('deliverBonusMoney').val(self.gameSetupObj.bonusMoney);
		iData.get('deliverBonusAmount').val(self.gameSetupObj.bonusAmount);
		iData.get('deliverGreenAmount').val(self.gameSetupObj.greenAmount);
		self.prepareShaking(self.hideSetting);
	});
	iData.get('deliverGreenMoney').maskInput();
	iData.get('deliverBonusMoney').maskInput();
	iData.get('deliverBonusAmount').maskInput();
	iData.get('deliverGreenAmount').maskInput();
	self.lockButtonSwitch();
}

deliver.prototype.updateSettingStatus = function(){
	var self = this;
	var inputArray = [iData.get('deliverGreenMoney'), iData.get('deliverBonusMoney'), iData.get('deliverBonusAmount'),iData.get('deliverGreenAmount')];
	self.checkSettingInput(inputArray,iData.get('deliverNow_setting_save'));
	
	if(!self.numericValidate([iData.get('deliverGreenMoney'), iData.get('deliverBonusMoney'), iData.get('deliverBonusAmount'),iData.get('deliverGreenAmount')])){
		iData.get('deliverNow_setting_save').addClass("disabled");
	}else{
		iData.get('deliverNow_setting_save').removeClass("disabled");
	}
}

deliver.prototype.checkSettingInput = function(inputArray,dimButton){
	var self= this;
	for(var i=0;i<inputArray.length;i++){
		if(inputArray[i].val() == "" || inputArray[i].val() === undefined){
			dimButton.addClass("disabled");
			return
		}
		inputArray[i].val(self.validateAmount(inputArray[i].val()));
	}
	dimButton.removeClass("disabled");
}

deliver.prototype.validateAmount = function(number){
	number = number.replace(/\./g,'');
	if(number != '0'){
		number = number.replace(/^0+/g,'');
	}
	return number;
}

deliver.prototype.updateSettingLocation = function(locationArray){
	var self = this;
	var LocationOptionHtml = '';
	for(var i=0;i < locationArray.length; i++){
		var options = {
				locationValue: locationArray[i].value,
				locationName : locationArray[i].name,
				ccyValue:locationArray[i].ccy
		};
		LocationOptionHtml += self.parseTmplate(tmplate.deliverLocationOption,options);
	}
	
	
	iData.get('deliverLocation').empty().append(LocationOptionHtml);
}

deliver.prototype.parseTmplate = function (tmplHtml, options) {
    var html = tmplHtml;
    for (var key in options) {
        html = html.replace(new RegExp("@{" + key + "}", "gm"), options[key]);
    }
    return html;
}

// ==============================================================
// page parsing section [end]
// ==============================================================

deliver.prototype.showPageFromLoading = function (pageId) {
	var self=this;
	setTimeout('iFunction.delegate.viewIndex="'+pageId+'";iFunction.delegate.hideLoadingMask();',500);
}

deliver.prototype.openInfoSection = function(topDiv, bottomDiv, infoDiv){
	var self=this;
	iData.get('splitMask').addClass('hidden');
	infoDiv.removeClass('hidden');
	bottomDiv.animate({ 
		bottom: "-"+self.constants.splitPercent
	}, 500 ).addClass('shadow');
	topDiv.animate({ 
		top: "-"+self.constants.splitPercent
	}, 500 ).addClass('shadow');
}

deliver.prototype.closeInfoSection = function(topDiv, bottomDiv, infoDiv){
	var self=this;
	bottomDiv.animate({ 
		bottom: "0%"
	}, 500, function(){
		this.removeClass('shadow')
	});
	topDiv.animate({ 
		top: "0%"
	}, 500, function(){
		this.removeClass('shadow');
		iData.get('splitMask').removeClass('hidden');
		//infoDiv.addClass('hidden');
		// Nick added for goTo unlock list if sb. won bonus
		if (self.endGameBonusAmount > 0) {
			self.goTo("file:///web/postlogon/unlock/unlock.html?state="+getUrlValueByName('state'), true);
		} else
		// Nick added for goTo unlock list if sb. won bonus
		self.prepareShaking(self.hideResult, [infoDiv.find('div.ui-waiting'), infoDiv.find('div.ui-deliverResult')]);
	});	
}

deliver.prototype.showResult = function(waitingDiv,resultDiv){
	var self = this;
	waitingDiv.fadeOut('slow', function(){
		resultDiv.hide().removeClass('hidden').fadeIn('slow');
		setTimeout(function(){
			self.closeInfoSection(iData.get('deliverNow_topSection'), iData.get('deliverNow_bottomSection'), iData.get('deliverNow_info'));
		}, self.constants.resultDisplayDuration);
	});
	self.playSound('result');
}

deliver.prototype.hideResult = function(waitingDiv, resultDiv){
	waitingDiv.show();
	waitingDiv.removeClass('hidden');
	resultDiv.addClass('hidden');
}

deliver.prototype.lockButtonSwitch = function(){
	var self = this;
	var button = iData.get('deliverNow_btn_lock');
	var area = iData.get('deliverNow_btn_lock_area');
	var distance = button.closest('div').width() - button.outerWidth();
	self.gameSetupObj.isEnableBonus = button.hasClass('isOn');
	
	var hasTouch = 'ontouchstart' in window;
	var START_EV = hasTouch ? 'touchstart' : 'mousedown';
	var MOVE_EV = hasTouch ? 'touchmove' : 'mousemove';
	var END_EV = hasTouch ? 'touchend' : 'mouseup';
	var CANCEL_EV = hasTouch ? 'touchcancel' : 'mouseout';
	var startPoint;
	var isMoving = false;
	
	area.get(0).addEventListener(START_EV, function(e){
		startPoint = e.touches? e.touches[0].pageX : e.pageX;
	});
	area.get(0).addEventListener(MOVE_EV, function(e){
		var nowPoint = e.touches? e.touches[0].pageX : e.pageX;
		if(!startPoint){
			return ;
		}
		isMoving = true;
		if(self.gameSetupObj.isEnableBonus){
			if(startPoint - nowPoint > distance/2){
				button.removeClass('isOn').addClass('isOff');
				button.text(iData.get('i18n').off);
				self.gameSetupObj.isEnableBonus = button.hasClass('isOn');
				startPoint = null;
				setTimeout(function(){isMoving = false;}, 500);
			}
		}else{
			if(nowPoint - startPoint > distance/2){
				button.removeClass('isOff').addClass('isOn');
				button.text(iData.get('i18n').on);
				self.gameSetupObj.isEnableBonus = button.hasClass('isOn');
				startPoint = null;
				setTimeout(function(){isMoving = false;}, 500);
			}
		}
	});
	area.get(0).addEventListener(END_EV, function(e){
		var nowPoint = e.touches? e.touches[0].pageX : e.pageX;
		if(!startPoint){
			return ;
		}
		if(self.gameSetupObj.isEnableBonus){
			if(startPoint - nowPoint > distance/2){
				button.removeClass('isOn').addClass('isOff');
				button.text(iData.get('i18n').off);
				self.gameSetupObj.isEnableBonus = button.hasClass('isOn');
			}
		}else{
			if(nowPoint - startPoint > distance/2){
				button.removeClass('isOff').addClass('isOn');
				button.text(iData.get('i18n').on);
				self.gameSetupObj.isEnableBonus = button.hasClass('isOn');
			}
		}
		startPoint = null;
		setTimeout(function(){isMoving = false;}, 500);
	});
	area.get(0).addEventListener(CANCEL_EV, function(e){
		if(!startPoint){
			return ;
		}
		startPoint = null;
		setTimeout(function(){isMoving = false;}, 500);
	});
	area.click(function(e){
		if(isMoving){
			return ;
		}
		if(self.gameSetupObj.isEnableBonus){
			button.removeClass('isOn').addClass('isOff');
			button.text(iData.get('i18n').off);
			self.gameSetupObj.isEnableBonus = button.hasClass('isOn');
		}else{
			button.removeClass('isOff').addClass('isOn');
			button.text(iData.get('i18n').on);
			self.gameSetupObj.isEnableBonus = button.hasClass('isOn');
		}
	});
}

deliver.prototype.deliverNowInit = function(){
	var self = this;
	$('#deliverNow div.subPage[for=slide]').removeClass('hidden');
	$('#deliverNow div.subPage[for=split]').addClass('hidden');
}

deliver.prototype.showSetting = function(){
	var self = this;
	self.updateSettingStatus();
	iData.get("icon-shakeBoss-top").addClass('hidden');
	iData.get("icon-shakeBoss-bottom").addClass('hidden');
	$('#deliverNow_setting').removeClass('hidden');
}
//Bill implement the changes for sponsor code [start]
deliver.prototype.showChannelCodeInfo = function(){
	var self = this;
	$('#deliverNow_channelCodeInfo').removeClass('hidden');
}
deliver.prototype.hideChannelCodeInfo = function(){
	var self = this;
	$('#deliverNow_channelCodeInfo').addClass('hidden');
}
deliver.prototype.splitChannelCode = function(channelCode){
	var self=this;
	var code='';
	var codeArr=[];
	codeArr=channelCode.split("");
	code=codeArr[0]+codeArr[1]+"."+codeArr[2];
	return code;
}
//Bill implement the changes for sponsor code [end]
deliver.prototype.hideSetting = function(){
	var self = this;
	// change by daniel 
	$('#deliverNow_setting').addClass('hidden');
	iData.get("icon-shakeBoss-top").removeClass('hidden');
	iData.get("icon-shakeBoss-bottom").removeClass('hidden');
	// change by daniel end
}

deliver.prototype.numericValidate = function(inputList){
	var self = this;
	if(!$.isArray(inputList)){
		return ;
	}
	for(var i=0; i<inputList.length; i++){
		if(!/^[0-9]+$/.test(inputList[i].val())){
			return false;
		}
	}
	return true;
}

deliver.prototype.prepareShaking = function(nextFn, nextFnArgs){
	var self = this;
	self.registerShakeListenerBoss(nextFn, nextFnArgs);
}

deliver.prototype.cancelShaking = function(nextFn, nextFnArgs){
	var self = this;
	self.unRegisterShakeListener(nextFn, nextFnArgs);
}

deliver.prototype.displayErrorMsg = function(errType){
	var self = this;
	if(!errType){
		iData.get('deliverNow_errorInfo').find('div:nth-child(1) span').text(iData.get('i18n').err_networkUnavail);
		iData.get('deliverNow_errorInfo').find('div:nth-child(2) span').text(iData.get('i18n').err_checkNetwork);
	}
	iData.get('deliverNow_normalInfo').addClass('hidden');
	iData.get('deliverNow_errorInfo').removeClass('hidden');
}

deliver.prototype.displayNormalMsg = function(errType){
	var self = this;
	iData.get('deliverNow_errorInfo').addClass('hidden');
	iData.get('deliverNow_normalInfo').removeClass('hidden');
}

// ==============================================================
// Native hook call section [start]
// ==============================================================
deliver.prototype.callback4GetUserInfo = function(data){
	var self = this;
	var keyNames = self.getCustomerInfoKeys();
	self.userInfo = data;
	self.gameSetupObj.location = self.userInfo[keyNames.location];
	for(var i = 0; i < self.configuration.settings.GreenPacketLocation.length; i++){
		if(self.configuration.settings.GreenPacketLocation[i].value === self.gameSetupObj.location){
			self.gameSetupObj.currency = self.configuration.settings.GreenPacketLocation[i].ccy;
		}
	}
	if(self.userInfo && self.userInfo[keyNames.secureToken]){
		if(self.configuration.settings.isBrowser){
			self.callback4GetEncryptedDeviceId('E812H39DK2L,9247611KDL01L23302138DDDF');
		}else{
			self.getEncryptedDeviceId(self.callback4GetEncryptedDeviceId);
		}
	}else{
		$('div.ui-error-panel>p').html(self._err['noService']);
		self.showPageFromLoading('errorWrapper');
	}
}

deliver.prototype.callback4GetEncryptedDeviceId = function(data){
	var self = this;
	self.deviceId = data;
	if(self.deviceId){
		if(self.configuration.settings.isBrowser){
			self.callback4GetSetting();
			//self.callback4GetSetting('');
		}else{
			self.getter(self.constants.settingName,self.callback4GetSetting);
		}
	}else{
		$('div.ui-error-panel>p').html(self._err['noService']);
		self.showPageFromLoading('errorWrapper');
	}
}

deliver.prototype.setSetting = function(){
	var self = this;
	//Bill updated for getGameBudget [start]
	self.getGameBudget();
	//Bill updated for getGameBudget [end]
	if(self.configuration.settings.isBrowser){
		self.callback4SetSetting(self.gameSetupObj);
	}else{
		self.setter(self.constants.settingName, JSON.stringify(self.gameSetupObj), self.callback4SetSetting);
	}
}

deliver.prototype.callback4SetSetting = function(){
	var self = this;
	self.prepareShaking(self.hideSetting);
}

deliver.prototype.callback4GetSetting = function(data){
	var self = this;
	var settingObj = {}
	try{
		settingObj = $.parseJSON(data);
	}catch(e){
	}
	if(!settingObj){
		settingObj = {
		location:self.gameSetupObj.location,
		greenAmount : self.gameSetupObj.greenAmount,
		bonusAmount : "5",
		currency : self.gameSetupObj.currency,
		greenMoney : "20",
		bonusMoney : "50"
		};
	}
	self.gameSetupObj.location = settingObj.location;
	self.gameSetupObj.greenMoney = settingObj.greenMoney;
	self.gameSetupObj.bonusMoney = settingObj.bonusMoney;
	self.gameSetupObj.bonusAmount = settingObj.bonusAmount;
	self.gameSetupObj.greenAmount = settingObj.greenAmount;
	self.gameSetupObj.currency = settingObj.currency;
	self.prepareShaking(self.showPageFromLoading, ['deliverNow']);
}

//Bill updated for getGameBudget [start]
deliver.prototype.getGameBudget = function(){
	var self = this;
	if(self.configuration.settings.dummy){
		console.log(self.getParam4GetGameBudget());
	}
	self.request({
		name: "getGameBudget",
		data: self.getParam4GetGameBudget,
		callback: self.callback4GetGameBudget,
		method: "post"
	});
}
deliver.prototype.getParam4GetGameBudget = function(){
	var self = this;
	return {
		"requestName"	: "getGameBudget",
		"account"		: self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.account],
		"secureToken"	: self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.secureToken],
		"deviceId"		: self.deviceId,
		"location"		: self.gameSetupObj.location
	};
}
deliver.prototype.callback4GetGameBudget = function(){
	var self = this;
	return {
		"success":function(callback){
			var data = callback.data;
			self._gameBudget = data.body.gameBudget;
			for(var i = 0; i < self.configuration.settings.GreenPacketLocation.length; i++){
				for(var j = 0; j < self._gameBudget.length; j++){
					if(self.configuration.settings.GreenPacketLocation[i].value === self.gameSetupObj.location){
						//alert("i:"+i+",j:"+j);
						self._totalBudget=self._gameBudget[i].totalBudget;
						self._remainBudget=self._gameBudget[i].remainBudget;
						self.gameSetupObj.currency = self.configuration.settings.GreenPacketLocation[i].ccy;
						iData.get('totalBudget').text(self._totalBudget+" "+self.gameSetupObj.currency);
						iData.get('remainBudget').text(self._remainBudget+" "+self.gameSetupObj.currency);
					}
				}
			}
		},
		"error":function(callback){
			var data=callback.data;
		}
	};
}
//Bill updated for getGameBudget [end]

deliver.prototype.registerShakeListenerBoss = function(nextFn, nextFnArgs){
	var self = this;
	if(!nextFnArgs){
		nextFnArgs = [];
	}
	if(!nextFn){
		nextFn = self.pseudoCallback;
	}
	if(self.configuration.settings.isBrowser){
		self.registerShakeListener(self.listener4RegisterShakeListener, function(){
			nextFn.apply(this, nextFnArgs);
		});
		(function(){
			nextFn.apply(self, nextFnArgs);
		})();

        //boss shake testing start
        console.log('going to register onclick event');
        $('#deliverNow').on('click', '#splitMask', function() {
            self.listener4RegisterShakeListener();
            //dave

            self.surplusMoney=10;
            if(self.surplusMoney <= 100){
                $('#sendingLaiseesMsg_div').show();
            }else{
                $('#sendingLaiseesMsg_div').hide();
            }
        });

        //boss shake testing start

	}else{
		// self.registerShakeListener(self.listener4RegisterShakeListener, function(){
		// 	nextFn.apply(this, nextFnArgs);
		// });
		// Nick updated to added support for shake extend
		self.registerShakeListener(self.startShakeGame, function() {
			nextFn.apply(this, nextFnArgs);
		});
	}
}
deliver.prototype.listener4RegisterShakeListener = function(){
	var self = this;
	self.cancelShaking(self.startShakeGame);
}

deliver.prototype.unRegisterShakeListener = function(nextFn, nextFnArgs){
	var self = this;
	if(!nextFnArgs){
		nextFnArgs = [];
	}
	if(!nextFn){
		nextFn = self.pseudoCallback;
	}
	if(self.configuration.settings.isBrowser){
		(function(){
			nextFn.apply(self, nextFnArgs);
		})();
	}else{
		self.unregisterShakeListener(function(){
			nextFn.apply(this, nextFnArgs);
		});
	}
}

deliver.prototype.playSound = function(type){
	var self = this;
	if(self.configuration.settings.isBrowser){
		;
	}else{
		self.playSoundByType(type);
	}
}

deliver.prototype.callback4SetGameId = function(){
	var self = this;
	self.openInfoSection(iData.get('deliverNow_topSection'), iData.get('deliverNow_bottomSection'), iData.get('deliverNow_info'));
}

deliver.prototype.pseudoCallback = function(){
}

// ==============================================================
// Native hook call section [end]
// ==============================================================


// ==============================================================
// JSON proxy call section [start]
// ==============================================================
deliver.prototype.startShakeGame = function(){
	var self = this;
	if(self.configuration.settings.dummy){
		console.log(self.getParam4StartShakeGame());
	}
	self.request({
		name: "startShakeGame",
		data: self.getParam4StartShakeGame,
		callback: self.callback4StartShakeGame,
		method: "post"
	});
}
deliver.prototype.getParam4StartShakeGame = function(){
	var self = this;
	var returnObj = {
		"requestName"	: "startGame",
		"account"		: self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.account],
		"secureToken"	: self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.secureToken],
		"deviceId"		: self.deviceId,
		"isBonusLocked" : true,// TODO to be removed
		"bonusAmount" : self.gameSetupObj.isEnableBonus ? self.gameSetupObj.bonusAmount : '0',
		"currency" : self.gameSetupObj.currency,
		"greenMoney" : self.gameSetupObj.greenMoney,
		"bonusMoney" : self.gameSetupObj.bonusMoney,
		"location" : self.gameSetupObj.location
	};
	
	if (self.gameSetupObj.greenAmount != "" && (/^[0-9]+$/.test([self.gameSetupObj.greenAmount]))) {
		returnObj['greenAmount'] = self.gameSetupObj.greenAmount;
	}
	return returnObj;
}
deliver.prototype.callback4StartShakeGame = function(){
	var self = this;
	return {
		"success":function(callback){
			var data = callback.data;
			console.log("data.body", data.body);
			self.gameId = data.body.gameId;
			// Nick added
			self.duration = data.body.duration;
            var switchText = iData.get('deliverNow_btn_lock').text();
            //new
            if(switchText=='N')
                switchText = 'No';
            else if(switchText=='Y')
                switchText = 'Yes';
            else
                console.log('只有Yes和No两种情况');

            iData.get('bonusLockSwitch').text(switchText);
			if(self.configuration.settings.isBrowser){
				console.log(self.configuration.settings.GreenPacket.gameId+', '+self.gameId);
				self.callback4SetGameId();
			}else{
				self.setter(self.configuration.settings.GreenPacket.gameId, self.gameId, self.callback4SetGameId);
			}
			var startTime = (new Date()).getTime();
			// var endTime = startTime + self.constants.waitingDuration;
			// Nick added to extend the duration
			var endTime = "";
			console.log("self.duration: " + self.duration);
			if (self.duration) {
				endTime = startTime + self.duration * 1000;
			} else {
				endTime = startTime + self.constants.waitingDuration;
			}
			console.log('from '+startTime+' to '+endTime);
			// TODO
			iData.get('countdownSpan').text(Math.round(self.constants.waitingDuration/1000));
			if (self.countdownID) {
				clearInterval(countdownID);
			}
			self.countdownID = setInterval(function(){
				var nowTime = (new Date()).getTime();
				var margin = endTime - nowTime;
				margin = Math.round(margin/1000);
				if(margin < 0 || margin > self.constants.waitingDuration){
					clearInterval(self.countdownID);
					self.countdownID = null;
					// self.endShakeGame();
					// Nick added to unRegisterShakeListener
					self.unRegisterShakeListener(self.endShakeGame);
					return ;
				}
				iData.get('countdownSpan').text(margin);
			}, 1000);
		},
		"error":function(callback){
			var data=callback.data;
			self.displayErrorMsg();
		}
	};
}

deliver.prototype.endShakeGame = function(){
	var self = this;
	if(self.configuration.settings.dummy){
		console.log(self.getParam4EndShakeGame());
	}
	self.request({
		name: "endShakeGame",
		data: self.getParam4EndShakeGame,
		callback: self.callback4EndShakeGame,
		method: "post"
	});
}
deliver.prototype.getParam4EndShakeGame = function(){
	var self = this;
	return {
		"requestName"	: "endGame",
		"account"		: self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.account],
		"secureToken"	: self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.secureToken],
		"deviceId"		: self.deviceId,
		"gameId"		: self.gameId
	};
}
deliver.prototype.callback4EndShakeGame = function(){
	var self = this;
	return {
		"success":function(callback){
			var data = callback.data;
			self.totalPrizeSent = data.body.totalPrizeSent;
			self.prizeSummary = data.body.prizeSummary;
			iData.get('sentLaiseeAmount').text(self.totalPrizeSent);
			for(var i = 0; i<self.prizeSummary.length; i++){
				if(self.prizeSummary[i].category == 'Green'){
					iData.get('greenAmount').text(self.prizeSummary[i].amount);
				}
				if(self.prizeSummary[i].category == 'Bonus'){
					iData.get('bonusAmount').text(self.prizeSummary[i].amount);
					// Nick added for goTo unlock list if sb. won bonus
					self.endGameBonusAmount = +self.prizeSummary[i].amount;
					// Nick added for goTo unlock list if sb. won bonus
				}
			}
		//Bill updated for getGameBudget [start]
		self.getGameBudget();
		//Bill updated for getGameBudget [end]
			self.showResult(iData.get('deliverNow_info').find('div.ui-waiting'), iData.get('deliverNow_info').find('div.ui-deliverResult'));
			self.displayNormalMsg();
		},
		"error":function(callback){
			var data=callback.data;
		//Bill updated for getGameBudget [start]
		self.getGameBudget();
		//Bill updated for getGameBudget [end]
			self.closeInfoSection(iData.get('deliverNow_topSection'), iData.get('deliverNow_bottomSection'), iData.get('deliverNow_info'));
			self.displayErrorMsg();
		}
	};
}

// ==============================================================
// JSON proxy call section [end]
// ==============================================================

//construct data model for the views
deliver.prototype.buildModel = function () {
    iData.add({
		"deliverNow_btn_menu":$('#deliverNow_btn_menu'),
		"deliverNow_btn_unlockBonus":$('#deliverNow_btn_unlockBonus'),
		"deliverNow_btn_dashboard":$('#deliverNow_btn_dashboard'),
		"deliverNow_btn_deliver":$('#deliverNow_btn_deliver'),
		"deliverNow_btn_lock":$('#deliverNow_btn_lock'),
		"deliverNow_btn_lock_area":$('#deliverNow_btn_lock_area'),
		"deliverNow_btn_setting":$('#deliverNow_btn_setting'),
		"deliverNow_topSection":$('#deliverNow_topSection'),
		"deliverNow_info":$('#deliverNow_info'),
		"deliverNow_bottomSection":$('#deliverNow_bottomSection'),
		"congratsMsg":$('#congratsMsg'),
		//"deliverLimit":$('#deliverLimit'),
		//"deliverBonus":$('#deliverBonus'),
		//"deliverCurrency":$('#deliverCurrency'),
		//"deliverAmount":$('#deliverAmount'),
		"deliverNow_setting_save":$('#deliverNow_setting_save'),
		"deliverNow_setting_cancel":$('#deliverNow_setting_cancel'),
		"sentLaiseeAmount":$('#sentLaiseeAmount'),
		"greenAmount":$('#greenAmount'),
		"bonusAmount":$('#bonusAmount'),
		"bonusLockSwitch":$('#bonusLockSwitch'),
		"deliverLocation":$('#deliverLocation'),
		"deliverCurrencyList":$('span[name="deliverCurrency"]'),
		"deliverGreenMoney":$('#deliverGreenMoney'),
		"deliverBonusMoney":$('#deliverBonusMoney'),
		"deliverBonusAmount":$('#deliverBonusAmount'),
		"deliverGreenAmount":$('#deliverGreenAmount'),
		"deliverNow_normalInfo":$('#deliverNow_normalInfo'),
		"deliverNow_errorInfo":$('#deliverNow_errorInfo'),
		"splitMask":$('#splitMask'),
		"countdownSpan":$('#countdownSpan'),
		"deliverNow_input_warpper":$('#deliverNow_input_warpper'),
		"uniqCode":$('#uniqCode'),
		"deliverNow_btn_info":$('#deliverNow_btn_info'),
		"deliverNow_channelCodeInfo_close":$('#deliverNow_channelCodeInfo_close'),
		"deliverNow_channelCode":$('#deliverNow_channelCode'),
		"icon-shakeBoss-top":$('.icon-shakeBoss-top'),
		"icon-shakeBoss-bottom":$('.icon-shakeBoss-bottom'),
		"totalBudget":$('#totalBudget'),
		"remainBudget":$('#remainBudget'),
		"":$('#'),
		"":$('#'),
		"":$('#'),
		"":$('#'),
		"":$('#'),
		"":$('#'),
		"":$('#')
	});
}	

deliver.superclass = iFunction;
deliver.start = function () {
    return new deliver();
}
iClass(deliver);